package com.hcy.app.screen.cipher

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Save
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.rounded.LastPage
import androidx.compose.material.icons.rounded.Share
import androidx.compose.material.icons.rounded.ShortText
import androidx.compose.material.icons.rounded.Webhook
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.*
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.hcy.app.LocalNavController
import com.hcy.app.R
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Note_Edit(viewModel: CipherViewModel= hiltViewModel(),noteId: Long=0){
    val navController = LocalNavController.current
    val context = LocalContext.current
    val focusManager = LocalFocusManager.current

    var showMenu by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()

    var titleText by remember { mutableStateOf(TextFieldValue("")) }
    var contentText by remember { mutableStateOf(TextFieldValue( "" )) }
    var currentNote by remember { mutableStateOf<NoteItem>(NoteItem(0,"","","", System.currentTimeMillis()/1000L,0,0,0)) } // 当前笔记ID，如果是新增的，id就是0

    val textNum = contentText.text.length
    var timeNum by remember { mutableLongStateOf(currentNote.createAt) }

    var hasChanges by remember { mutableStateOf(false) }


    LaunchedEffect(Unit) {
        if ( noteId !=0L ){
            currentNote = viewModel.getNoteDetailById(noteId)
            contentText = TextFieldValue( currentNote.content )
            titleText = TextFieldValue( currentNote.title )
            timeNum = currentNote.createAt
        }
    }


    Column(
        modifier = Modifier.fillMaxSize().systemBarsPadding().background(Color(0xFFF6F6F5))
    ){
        // 顶部工具栏
        Row {
            TopAppBar(
                title = {},
                navigationIcon = {
                    IconButton(onClick = {
                        navController.navigate("cipher/home")
                    }) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "后退",
                            modifier = Modifier.size(30.dp),
                            tint = Color.Black
                        )
                    }
                },
                actions = {
                    // 菜单
                    if (hasChanges){
                        IconButton(
                            onClick = {
                                scope.launch {
                                    currentNote.title = titleText.text
                                    currentNote.content = contentText.text
                                    currentNote.updateAt = System.currentTimeMillis()/1000L
                                    currentNote.id = viewModel.saveNote(currentNote)
                                    focusManager.clearFocus() // 移除所有焦点
                                    hasChanges = false
                                }
                            }
                        ) {
                            Icon(
                                imageVector = Icons.Default.Save,
                                contentDescription = "保存",
                                modifier = Modifier.size(30.dp),
                                tint = Color.Black
                            )
                        }
                    }
                    IconButton(onClick = {  }) {
                        Icon(
                            imageVector = Icons.Default.Share,
                            contentDescription = "分享",
                            modifier = Modifier.size(30.dp),
                            tint = Color.Black
                        )
                    }
                    IconButton(onClick = { showMenu = true }) {
                        Icon(
                            imageVector = ImageVector.vectorResource(id = R.drawable.lock),
                            contentDescription = "更多",
                            modifier = Modifier.size(30.dp),
                            tint = Color.Black
                        )
                    }
                    // 更多菜单
                    DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
                        //item还有一些其他属性，不一一演示
                        DropdownMenuItem(
                            text = { Text(text = "打开链接") },
                            onClick = { showMenu = false },
                            leadingIcon = {
                                Icon(
                                    imageVector = Icons.Rounded.Webhook,
                                    contentDescription = ""
                                )
                            },
                            trailingIcon = {
                                Icon(
                                    imageVector = Icons.Rounded.LastPage,
                                    contentDescription = ""
                                )
                            }
                        )
                        DropdownMenuItem(
                            text = { Text(text = "分享App") },
                            onClick = { showMenu = false },
                            leadingIcon = {
                                Icon(
                                    imageVector = Icons.Rounded.Share,
                                    contentDescription = ""
                                )
                            },
                            trailingIcon = {
                                Icon(
                                    imageVector = Icons.Rounded.ShortText,
                                    contentDescription = ""
                                )
                            }
                        )
                    }
                }
            )
        }

        // 提示信息
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(" 时间：${timestampToDateTime(timeNum,true)}")
            VerticalDivider(
                modifier = Modifier.height(12.dp).padding(start = 5.dp, end = 5.dp)
            )
            Text( "${textNum}字")
        }
        HorizontalDivider(
            modifier = Modifier.padding(5.dp)
        )
        // 标题
        OutlinedTextField(
            value = titleText,
            onValueChange = {
                titleText = it
                hasChanges = true
                            },
            modifier = Modifier.fillMaxWidth(),
            label = { Text("笔记标题") },
            textStyle = TextStyle(
                fontWeight = FontWeight.Bold,
                fontSize = 20.sp
            ),
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = MaterialTheme.colorScheme.primary,
                unfocusedBorderColor = MaterialTheme.colorScheme.outline
            ),

        )

        // 内容区（正常字体+可滚动）
        OutlinedTextField(
            value = contentText,
            onValueChange = {
                contentText = it
                hasChanges = true
                            },
            label = { Text("笔记内容") },
            textStyle = TextStyle(
                fontWeight = FontWeight.Normal,
                fontSize = 16.sp
            ),
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .heightIn(min = 200.dp),
            singleLine = false,
            maxLines = 20,
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = MaterialTheme.colorScheme.secondary,
                unfocusedBorderColor = MaterialTheme.colorScheme.outlineVariant
            )
        )
    }
}

fun timestampToDateTime(timestamp: Long, isSeconds: Boolean = false): String {
    val timeInMillis = if (isSeconds) timestamp * 1000 else timestamp
    val date = Date(timeInMillis)
    val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
    return formatter.format(date)
}